<template>
  <view class="comment-list-page" :style="{'--primary-color': primaryColor}">
    
    <!-- 商品信息卡片 -->
    <view class="product-card">
      <view class="card-header">
        <text class="card-title">{{ productName }}</text>
        <text class="card-subtitle">共 {{ totalComments }} 条评价</text>
      </view>
    </view>
    
    <!-- 筛选卡片 -->
    <view class="filter-card">
      <view class="card-header">
        <text class="card-title">筛选条件</text>
        <text class="card-subtitle">选择要查看的评价类型</text>
      </view>
      <view class="filter-tabs">
        <view 
          class="tab-item" 
          :class="{ 'active': currentFilter === index }"
          v-for="(filter, index) in filters" 
          :key="index"
          @click="switchFilter(index)"
        >
          <text class="tab-text">{{ filter.name }}</text>
          <view class="tab-indicator" v-if="currentFilter === index"></view>
        </view>
      </view>
      
      <!-- 星级筛选 -->
      <view class="star-filter">
        <text class="filter-label">星级筛选</text>
        <view class="star-options">
          <view 
            class="star-option"
            :class="{ 'active': selectedStar === star }"
            v-for="star in starOptions"
            :key="star"
            @click="selectStar(star)"
          >
            <text class="star-text">{{ star === 0 ? '全部' : star + '星' }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 评价列表 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y
    >
      <view class="comment-list">
        <view 
          class="comment-card" 
          v-for="comment in commentList" 
          :key="comment.id"
          @click="goToCommentDetail(comment)"
        >
          <!-- 评价头部 -->
          <view class="comment-header">
            <view class="user-info">
              <text class="username">{{ comment.userName }}</text>
              <view class="rating">
                <text 
                  class="star" 
                  :class="{ 'active': index <= comment.rating }"
                  v-for="index in 5" 
                  :key="index"
                >★</text>
              </view>
            </view>
            <text class="comment-time">{{ comment.createTime }}</text>
          </view>
          
          <!-- 评价内容 -->
          <view class="comment-content">
            <text class="comment-text">{{ comment.content }}</text>
          </view>
          
          <!-- 评价图片 -->
          <view class="comment-images" v-if="comment.images && comment.images.length > 0">
            <image 
              class="comment-image" 
              v-for="(image, index) in comment.images" 
              :key="index"
              :src="image"
              mode="aspectFill"
              @click.stop="previewImage(comment.images, index)"
            />
          </view>
          
          <!-- 商户回复 -->
          <view class="merchant-reply" v-if="comment.merchantReply">
            <view class="reply-header">
              <text class="reply-label">商户回复</text>
            </view>
            <text class="reply-content">{{ comment.merchantReply }}</text>
          </view>
        </view>
      </view>
      

      
      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && commentList.length === 0">
        <text class="empty-text">暂无评价数据</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getCommentList, getCommentsByProductId } from '@/api/comment'
import { API_CONFIG } from '@/config/api'
import browseTracker from '@/utils/browseTracker'
import { getToken, getUserInfo } from '@/utils/auth'
import { getThemePrimaryColor, getThemeColorFromGlobal } from '@/utils/theme'

export default {
  data() {
    return {
      productId: '',
      productName: '',
      totalComments: 0,
      currentFilter: 0,
      selectedStar: 0,
      commentList: [],
      allCommentList: [], // 存储所有评价数据用于前端筛选
      loading: false,
      filters: [
        { name: '全部', value: 'all' },
        { name: '有商家回复', value: 'replied' },
        { name: '无商家回复', value: 'no_reply' }
      ],
      starOptions: [0, 1, 2, 3, 4, 5],
      themeColor: '1' // 主题色编号
    }
  },
  
  computed: {
    // 动态获取主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    // 主题色样式
    themeColorStyles() {
      const styles = this.setThemeColorVariables(this.primaryColor)
      return {
        '--primary-color': styles.primaryColor,
        '--primary-color-light': styles.primaryColorLight,
        '--primary-color-glow': styles.primaryColorGlow,
        '--primary-color-shadow': styles.primaryColorShadow,
        '--background-gradient': styles.backgroundGradient,
        '--card-shadow': styles.cardShadow,
        '--card-border': styles.cardBorder,
        '--tab-active-bg': styles.tabActiveBg,
        '--star-active-bg': styles.starActiveBg,
        '--reply-border-color': styles.replyBorderColor
      }
    }
  },
  
  onLoad(options) {
    this.initThemeColor()
    this.productId = options.productId || ''
    this.productName = decodeURIComponent(options.productName || '商品评价')
    
    // 检查productId是否有效
    if (!this.productId || this.productId === 'undefined') {
      uni.showToast({
        title: '商品信息错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    this.startBrowseTracking();
    this.loadCommentList()
  },
  
  onShow() {
    browseTracker.resume();
  },
  
  onHide() {
    browseTracker.pause();
  },
  
  onUnload() {
    browseTracker.stopTracking();
  },
  
  beforeDestroy() {
    browseTracker.stopTracking();
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 切换筛选条件
    switchFilter(index) {
      this.currentFilter = index
      this.filterComments()
    },
    
    // 选择星级
    selectStar(star) {
      this.selectedStar = star
      this.filterComments()
    },
    
    // 前端筛选评价
    filterComments() {
      let filteredList = [...this.allCommentList]
      
      // 按评价类型筛选
      if (this.currentFilter === 1) { // 好评
        filteredList = filteredList.filter(comment => comment.star >= 4)
      } else if (this.currentFilter === 2) { // 中评
        filteredList = filteredList.filter(comment => comment.star === 3)
      } else if (this.currentFilter === 3) { // 差评
        filteredList = filteredList.filter(comment => comment.star <= 2)
      } else if (this.currentFilter === 4) { // 有商家回复
        filteredList = filteredList.filter(comment => comment.merchantReply && comment.merchantReply.trim() !== '')
      } else if (this.currentFilter === 5) { // 无商家回复
        filteredList = filteredList.filter(comment => !comment.merchantReply || comment.merchantReply.trim() === '')
      }
      
      // 按星级筛选
      if (this.selectedStar > 0) {
        filteredList = filteredList.filter(comment => comment.star === this.selectedStar)
      }
      
      this.commentList = filteredList
      console.log('筛选完成，结果数量:', filteredList.length)
    },
    
    // 处理评价数据
    async processCommentList(commentList) {
      if (!commentList || !Array.isArray(commentList)) {
        return []
      }
      
      const processedComments = []
      
      for (const comment of commentList) {
        // 处理评论图片
        let images = []
        const imageData = comment.images || comment.image
        if (imageData) {
          if (Array.isArray(imageData)) {
            images = imageData.map(img => this.processImageUrl(img)).filter(img => img)
          } else if (typeof imageData === 'string') {
            images = imageData.split(',').map(img => {
              return this.processImageUrl(img.trim())
            }).filter(img => img)
          }
        }
        
        // 转换字段名称（数据库下划线命名转为前端驼峰命名）
        processedComments.push({
          id: comment.comment_id || comment.commentId || comment.id,
          productId: comment.product_id || comment.productId,
          orderId: comment.order_id || comment.orderId,
          userId: comment.user_id || comment.userId,
          userName: comment.user_name || comment.userName || '匿名用户',
          userAvatar: comment.user_avatar || comment.userAvatar || '/static/images/default-avatar.png',
          rating: comment.star || 5,
          star: comment.star || 5,
          content: comment.content || '',
          images: images,
          createTime: comment.create_time ? this.formatDate(comment.create_time) : (comment.createTime ? this.formatDate(comment.createTime) : ''),
          reply: comment.reply_content || comment.replyContent || comment.merchantReply || '',
          merchantReply: comment.reply_content || comment.replyContent || comment.merchantReply || '',
          replyTime: comment.reply_time || comment.replyTime,
          showStatus: comment.show_status || comment.showStatus
        })
      }
      
      return processedComments
    },
    
    // 重置并加载
    async resetAndLoad() {
      console.log('重置并加载数据')
      
      // 清除相关缓存
      const productCacheKey = `comment_detail_${this.productId}`
      const allCommentsKey = `all_comments_${this.productId}`
      try {
        uni.removeStorageSync(productCacheKey)
        uni.removeStorageSync(allCommentsKey)
        console.log('已清除评价缓存')
      } catch (e) {
        console.log('清除评价缓存失败:', e)
      }
      
      // 重置状态
      this.currentFilter = 0
      this.selectedStar = 0
      this.commentList = []
      this.allCommentList = []
      this.totalComments = 0
      
      // 重新加载所有数据
      await this.loadCommentList(true)
    },
    

    

    
    // 加载评价列表
    async loadCommentList(forceRefresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      // 定义缓存键（只缓存所有数据，不按筛选条件缓存）
      const productCacheKey = `comment_detail_${this.productId}`
      const allCommentsKey = `all_comments_${this.productId}`
      
      try {
        // 如果已有所有数据且不是强制刷新，直接进行前端筛选
        if (!forceRefresh && this.allCommentList.length > 0) {
          this.filterComments()
          this.loading = false
          return
        }
        
        // 如果不是强制刷新，尝试从缓存获取所有数据
        if (!forceRefresh) {
          // 首先尝试从商品详情页面的缓存获取数据
          const productComments = uni.getStorageSync(productCacheKey)
          if (productComments && Array.isArray(productComments)) {
            console.log('从商品详情缓存获取评价数据:', productComments)
            this.allCommentList = await this.processCommentList(productComments)
            this.filterComments()
            this.loading = false
            return
          }
          
          // 尝试从所有评价缓存获取数据
          const allComments = uni.getStorageSync(allCommentsKey)
          if (allComments && Array.isArray(allComments)) {
            console.log('从所有评价缓存获取数据:', allComments)
            this.allCommentList = allComments
            this.filterComments()
            this.loading = false
            return
          }
        }
        
        // 请求所有评价数据（不带筛选条件）
        const params = {
          productId: this.productId,
          page: 1,
          pageSize: 1000  // 获取大量数据，避免分页
        }
        
        const response = await getCommentList(params)
        console.log('评价列表API响应:', response)
        
        if (response && response.code === 200) {
          // getCommentList 返回的是分页结构 {data: {total, rows}, code, msg}
          const responseData = response.data || {}
          const commentList = responseData.rows || []
          console.log('获取到的评价数据:', commentList)
          
          // 处理评价数据
          this.allCommentList = await this.processCommentList(commentList)
          this.totalComments = responseData.total || 0
          
          // 缓存所有评价数据
          uni.setStorageSync(allCommentsKey, this.allCommentList)
          uni.setStorageSync(productCacheKey, commentList)
          
          // 进行前端筛选
          this.filterComments()
          
          console.log('所有评价数据已加载，总数:', this.allCommentList.length)
        } else {
          console.error('获取评价列表失败:', response)
          this.$modal.showToast(response?.msg || '获取评价列表失败')
          this.commentList = []
          this.allCommentList = []
          this.totalComments = 0
        }
      } catch (error) {
        console.error('获取评价列表失败:', error)
        this.$modal.showToast('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    

    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        current: current,
        urls: images
      })
    },
    
    // 跳转到评论详情
    goToCommentDetail(comment) {
      uni.navigateTo({
        url: `/pages/comment/detail?commentId=${comment.id}&productId=${this.productId}`
      })
    },
    
    // 处理图片URL
     processImageUrl(imagePath) {
       if (!imagePath) return ''
       
       // 如果已经是完整的URL，直接返回
       if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
         return imagePath
       }
       
       // 处理服务器路径
       let serverUrl = API_CONFIG.SERVER_IP
       
       // 如果包含/dev-api，替换成/
       if (imagePath.includes('/dev-api')) {
         imagePath = imagePath.replace('/dev-api', '')
       }
       
       // 确保路径以/开头
       if (!imagePath.startsWith('/')) {
         imagePath = '/' + imagePath
       }
       
       return serverUrl + imagePath
     },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      
      try {
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return dateStr
        
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        
        return `${year}-${month}-${day} ${hours}:${minutes}`
      } catch (error) {
        console.error('日期格式化失败:', error)
        return dateStr
      }
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.themeColor = themeColor
          console.log('异步获取主题色 - 评论列表页面:', themeColor)
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.themeColor = themeColor
          console.log('同步获取主题色 - 评论列表页面:', themeColor)
        }
      } catch (error) {
        console.error('评论列表页面主题色初始化失败:', error)
        // 使用默认主题色
        this.themeColor = '1'
      }
    },
    
    // 设置主题色变量
    setThemeColorVariables(color) {
      const rgb = this.hexToRgb(color)
      const lightColor = this.lightenColor(color, 0.85)
      const glowColor = this.lightenColor(color, 0.20)
      
      // 设置CSS变量（兼容小程序和H5）
      // #ifdef H5
      if (typeof document !== 'undefined') {
        const root = document.documentElement
        root.style.setProperty('--primary-color', color)
        root.style.setProperty('--primary-color-light', lightColor)
        root.style.setProperty('--primary-color-glow', glowColor)
        root.style.setProperty('--primary-color-shadow', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`)
      }
      // #endif
      
      return {
        primaryColor: color,
        primaryColorLight: lightColor,
        primaryColorGlow: glowColor,
        primaryColorShadow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
        backgroundGradient: `linear-gradient(135deg, ${lightColor} 0%, #F8F9FA 100%)`,
        cardShadow: `0 8rpx 32rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        cardBorder: `1rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        tabActiveBg: `linear-gradient(135deg, ${color} 0%, ${this.darkenColor(color, 0.15)} 100%)`,
        starActiveBg: `linear-gradient(135deg, ${color} 0%, ${this.darkenColor(color, 0.15)} 100%)`,
        replyBorderColor: color
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 74, g: 144, b: 226 }
    },
    
    // 颜色加深
    darkenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      const factor = 1 - percent
      const r = Math.round(rgb.r * factor)
      const g = Math.round(rgb.g * factor)
      const b = Math.round(rgb.b * factor)
      return `rgb(${r}, ${g}, ${b})`
    },
    
    // 颜色变浅
    lightenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      const factor = percent
      const r = Math.round(rgb.r + (255 - rgb.r) * factor)
      const g = Math.round(rgb.g + (255 - rgb.g) * factor)
      const b = Math.round(rgb.b + (255 - rgb.b) * factor)
      return `rgb(${r}, ${g}, ${b})`
    },

    // 开始浏览时长记录
    startBrowseTracking() {
      const token = getToken();
      const userInfo = getUserInfo();
      if (token && userInfo && userInfo.userId) {
        browseTracker.startTracking({
          pageType: 'comment',
          pageName: '评价列表',
          pageUrl: '/pages/comment/list',
          productId: this.productId,
          productName: this.productName
        }, userInfo.userId);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.comment-list-page {
  min-height: 100vh;
  background: #ffffff;
  padding: 20rpx 0;
  
  .product-card, .filter-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 16rpx;
    margin: 0 30rpx 20rpx;
    padding: 30rpx;
    box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.1);
    border: 1rpx solid rgba(74, 144, 226, 0.1);
    transition: all 0.3s ease;
    
    .card-header {
      margin-bottom: 20rpx;
      
      .card-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .card-subtitle {
        font-size: 24rpx;
        color: #94a3b8;
      }
    }
  }
  
  .filter-tabs {
    display: flex;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .tab-item {
      flex: 1;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f8fafc;
      border-radius: 12rpx;
      position: relative;
      transition: all 0.3s ease;
      
      &.active {
        background: linear-gradient(135deg, var(--primary-color, #4A90E2) 0%, var(--primary-color, #4A90E2) 100%);
        
        .tab-text {
          color: #ffffff;
        }
      }
      
      .tab-text {
        font-size: 26rpx;
        color: #64748b;
        font-weight: 500;
        transition: color 0.3s ease;
      }
    }
  }
  
  .star-filter {
    .filter-label {
      font-size: 28rpx;
      color: #475569;
      font-weight: 500;
      display: block;
      margin-bottom: 15rpx;
    }
    
    .star-options {
      display: flex;
      gap: 15rpx;
      flex-wrap: wrap;
      
      .star-option {
        padding: 12rpx 20rpx;
        background: #f8fafc;
        border-radius: 20rpx;
        border: 1px solid #e2e8f0;
        transition: all 0.3s ease;
        
        &.active {
          background: linear-gradient(135deg, var(--primary-color, #4A90E2) 0%, var(--primary-color, #4A90E2) 100%);
          border-color: var(--primary-color, #4A90E2);
          
          .star-text {
            color: #ffffff;
          }
        }
        
        .star-text {
          font-size: 24rpx;
          color: #64748b;
          transition: color 0.3s ease;
        }
      }
    }
  }
  
  .content-scroll {
    height: calc(100vh - 200rpx);
  }
  
  .comment-list {
    padding: 0 30rpx 30rpx;
  }
  
  .comment-card {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.1);
    border: 1rpx solid rgba(74, 144, 226, 0.1);
    transition: all 0.3s ease;
    
    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.15);
    }
    
    .comment-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;
      
      .user-info {
        .username {
          font-size: 28rpx;
          font-weight: 600;
          color: #1e293b;
          display: block;
          margin-bottom: 8rpx;
        }
        
        .rating {
          display: flex;
          gap: 4rpx;
          
          .star {
            font-size: 24rpx;
            color: #e2e8f0;
            
            &.active {
              color: #fbbf24;
            }
          }
        }
      }
      
      .comment-time {
        font-size: 24rpx;
        color: #94a3b8;
      }
    }
    
    .comment-content {
      margin-bottom: 20rpx;
      
      .comment-text {
        font-size: 28rpx;
        color: #475569;
        line-height: 1.6;
      }
    }
    
    .comment-images {
      display: flex;
      gap: 10rpx;
      margin-bottom: 20rpx;
      flex-wrap: wrap;
      
      .comment-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
      }
    }
    
    .merchant-reply {
      background: #f8fafc;
      border-radius: 12rpx;
      padding: 20rpx;
      border-left: 4rpx solid var(--primary-color, #4A90E2);
      
      .reply-header {
        margin-bottom: 10rpx;
        
        .reply-label {
          font-size: 24rpx;
          color: var(--primary-color, #4A90E2);
          font-weight: 600;
        }
      }
      
      .reply-content {
        font-size: 26rpx;
        color: #475569;
        line-height: 1.5;
      }
    }
  }
  
  .load-more, .no-more, .empty-state {
    text-align: center;
    padding: 40rpx 0;
    
    .load-text, .no-more-text, .empty-text {
      font-size: 26rpx;
      color: #94a3b8;
    }
  }
}
</style>